﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartSpace.Core.Metadata;

namespace SmartSpace.Data
{
    /// <summary>
    /// 详细信息
    /// </summary>
    public class DataInstance
    {
        private Guid _id;

        /// <summary>
        /// 标识字段
        /// </summary>
        private FieldInstance _identityField;

        private FieldInstance _captionField;

        public EntityMetadata Entity { get; set; }
        public List<FieldInstance> Fields { get; set; }

        public FieldInstance GetIdentity()
        {
            if (Fields == null)
            {
                throw new Exception("数据实例还没有字段，没有发现Identity属性!");
            }

            if (_identityField == null)
            {
                foreach (FieldInstance field in Fields)
                {
                    if (field.Property.IsIdentity)
                    {
                        _identityField = field;
                        break;
                    }
                }
            }

            if (_identityField == null)
            {
                throw new Exception("没有发现Identity属性!");
            }
            return _identityField;
        }

        /// <summary>
        /// 标识字段
        /// </summary>
        public Guid Id
        {
            get
            {
                if (GetIdentity().Data == null)
                {
                    return default(Guid);
                }
                return (Guid)GetIdentity().Data;
            }
            set
            {
                FieldInstance.SetData(GetIdentity(), value.ToString(), value.ToString());
            }
        }
    }
}
